package com.hinner.config.security;

import cn.hutool.json.JSONUtil;
import com.hinner.common.Result;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * spring security 登录成功处理器
 */
@Component  //可以被自动导入
public class LoginFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        // 登录失败后的处理
        httpServletResponse.setContentType("application/json;charset=utf-8");
        ServletOutputStream out = httpServletResponse.getOutputStream();

        // 内容
        String msg = e.getMessage();
        if(e instanceof BadCredentialsException){
            msg = "用户名或密码错误";
        }
        byte[] bytes = JSONUtil.toJsonStr(Result.error(msg)).getBytes("UTF-8"); // 最后是防止中文乱码

        out.write(bytes);
        out.flush();
        out.close();
    }
}
